package com.heima.search.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(1)
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/*")
public class AppTokenFilter extends GenericFilter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.从请求头取出userId
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String userId = request.getHeader("userId");

        //2.封装对象
        if(StringUtils.isNotEmpty(userId) && !userId.equals("0")){  // 排除浏览访客
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));

            //3.把对象存入ThreadLocal
            ThreadLocalUtils.set(apUser);
        }

        //4.放行
        filterChain.doFilter(request,response);
    }
}
